<template>
  <el-tag class="tagDivision" v-for="(item,index) in articleTags" :key="index"
          closable
          @close="deleteTagHandler(item)"
  >
    {{ item }}
  </el-tag>
  <el-input class="inputTag"
            size="small"
            ref="inputTag"
            v-if="inputTagVisible && enableTag" v-model="inputTagValue"
            @keyup.enter="inputTagHandler"
            @focusout="inputTagHandler"
  ></el-input>
  <el-button v-if="!inputTagVisible && enableTag"
             size="small"
             @click="showInputTagHandler">+ 添加标签</el-button>
</template>

<script>
import { nextTick, ref } from 'vue'

export default {
  props: {
    modelValue: {
      default: ''
    },
    limit: {
      default: 5
    }
  },
  computed: {
    value: {
      get () {
        return this.modelValue
      },
      set (value) {
        this.$emit('update:modelValue', value)
      }
    }
  },
  name: 'input-tag-list',
  setup () {
    return {
      articleTags: ref([]),
      inputTagVisible: ref(false),
      inputTagValue: ref(''),
      enableTag: ref(true)
    }
  },
  methods: {
    getOptionedTags () {
      const art = {
        tag: this.articleTags
      }
      console.log(this.articleTags.toString())
      console.log(JSON.stringify(art))
      this.value = JSON.stringify(this.articleTags)
      return JSON.stringify(this.articleTags)
    },
    // 插入新的标签
    inputTagHandler () {
      if (this.inputTagValue) {
        this.inputTagValue = this.inputTagValue.replaceAll(' ', '')
        this.articleTags.push(this.inputTagValue)
        console.log(this.articleTags)
        this.getOptionedTags()
        if (this.articleTags.length >= this.limit) {
          this.enableTag = false
        }
      }
      this.inputTagVisible = false
      this.inputTagValue = ''
    },
    // 显示标签输入框
    showInputTagHandler () {
      this.inputTagVisible = true
      nextTick(() => {
        this.$refs.inputTag.input.focus()
      })
    },
    // 删除标签
    deleteTagHandler (val) {
      this.articleTags.splice(this.articleTags.indexOf(val), 1)
      this.getOptionedTags()
      if (this.articleTags.length < this.limit) {
        this.enableTag = true
      }
    }
  }
}
</script>

<style scoped>
.inputTag{
  width: 82px;
}
.tagDivision{
  margin-right: 5px;
}
</style>
